package com.example.arouter

import android.content.Context
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Interceptor
import com.alibaba.android.arouter.facade.callback.InterceptorCallback
import com.alibaba.android.arouter.facade.template.IInterceptor
import com.tencent.mmkv.MMKV
/**
 * 登录态的拦截器
 * */
@Interceptor(priority =5 ,name="路由Token拦截器" )
class RouterTokenInterceptor :IInterceptor{

    private lateinit var mContext : Context

    //白名单集合
    private val checkPath = arrayOf("/activity/detail")


    override fun init(context: Context?) {
       if (context!=null){
           mContext=context
       }
    }

    override fun process(postcard: Postcard, callback: InterceptorCallback) {

        try {

            if(checkPath.contains(postcard.path)){
                checkLoginToken(postcard,callback)
            }else{
                //继续执行
                callback.onContinue(postcard)
            }

        } catch (e: Exception) {
            e.printStackTrace()
            callback.onContinue(postcard)
        }
    }

    /**
     * 检测登录态
     */
    private fun checkLoginToken(postcard: Postcard, callback: InterceptorCallback) {
        val token =MMKV.defaultMMKV().decodeString("token","")
        if (token.isNullOrEmpty()){
            postcard.path="/activity/login"
            postcard.navigation()
        }else{
            callback.onContinue(postcard)
        }
    }

}